package com.summer.service.impl;

import com.github.pagehelper.PageInfo;
import com.summer.entity.OrderBorrow;
import com.summer.entity.UserInfo;
import com.summer.mapper.UserInfoMapper;
import com.summer.service.IUserInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Desc:用户的Service接口
 * Created by tl on 2018/12/20
 */
@Service
public class UserInfoService implements IUserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public PageInfo<UserInfo> queryWithBorrow(Map<String, Object> params) {
        List<UserInfo> list = userInfoMapper.findOrder(params);
        //get latest order
        Iterator<UserInfo> iterator = list.iterator();
        while (iterator.hasNext()) {
            UserInfo next = iterator.next();
            if (null != next && !CollectionUtils.isEmpty(next.getOrderBorrowList())) {
                List<OrderBorrow> assetBorrowOrderList = next.getOrderBorrowList();
                List<OrderBorrow> orders =
                        assetBorrowOrderList.stream().sorted(Comparator.comparing(OrderBorrow::getApplyTimeChg).reversed()).collect(Collectors.toList());
                assetBorrowOrderList.clear();
                assetBorrowOrderList.add(orders.get(0));
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(UserInfo record) {
        return userInfoMapper.insert(record);
    }

    @Override
    public List<UserInfo> findOrder(Map<String, Object> params) {
        return userInfoMapper.findOrder(params);
    }

    @Transactional
    @Override
    public int insertSelective(UserInfo record) {
        return userInfoMapper.insertSelective(record);
    }

    @Override
    public UserInfo selectByPrimaryKey(Integer id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(UserInfo record) {
        return userInfoMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public List<UserInfo> selectSimple(Map<String, Object> params) {
        return userInfoMapper.selectSimple(params);
    }

    @Override
    public int updateByPrimaryKey(UserInfo record) {
        return userInfoMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<UserInfo> findParams(Map<String, Object> params) {
        return userInfoMapper.findParams(params);
    }

}
